from PIL import Image
from PIL import ImageDraw
import sys
import os
import subprocess
# 使用pillow读取图片，获取图片的宽和高
# def findAllfile(base):
# 	for root,ds,fs in os.walk(base):
# 		for f in fs:
# 			yield f

def check_img(number,image_path):
	img = {}
	xml = []
	status = 1
	print("image path %s"%image_path)
	img_pillow = Image.open(image_path)
	xml_path = "%s/xml/%s.xml"%(image_path[:-9],image_path[-8:-4])
	print("xml path %s"%xml_path)
	# img['width'] = img_pillow.width # 图片宽度
	# img['height'] = img_pillow.height # 图片高度

	# ret = subprocess.run("grep -A 1 '<width>' annotations/%s.xml|cut -d\> -f 2|cut -d\< -f 1 "%image_path[-8:-4],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
	# if ret.returncode == 0:
	#     xml = ret.stdout.split("\n")
	#     # print(xml)
	# else:
	#     print("error:",ret)

	# if img['width'] == int(xml[0]) and img['height'] == int(xml[1]):
	# 	print("%d  %s is ok"%(number,image_path))
	# 	status = 1
	# 	# print("img:%d,%d"%(img['width'],img['height']))
	# 	# print("xml:%s,%s"%(xml[0],xml[1]))
	# else:
	# 	print()
	# 	print("%d,%s is error   "%(number,image_path))
	# 	print("%d,%s,%d,%s"%(img['width'],xml[0],img['height'],xml[1]))
	# 	print()

	ret2 = subprocess.run("grep -A 3 '<xmin>' %s|cut -d\> -f 2|cut -d\< -f 1 "%xml_path,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
	if ret2.returncode == 0:
	    point = ret2.stdout.split("\n")
	    # print(point)
	else:
	    print("error:",ret2)

	return status,point,img_pillow



#遍历图片目录
#eg：python imgwh.py images/
base=sys.argv[1]
number = 0
#遍历图片目录创建文件列表
#eg：python imgwh.py images/
file_list = []
for line in os.listdir(base):
    file_list.append(line)

ret = subprocess.run("cat log.txt|cut -d: -f 1",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
if ret.returncode == 0:
    tlist = ret.stdout.split()
    print(tlist)
else:
    print("error:",ret)

# 打开一个文件
fo = open("log.txt", "a+")
for line in file_list:
	number += 1
	if line == "xml":
		continue
	if not tlist.count(line):
		
		image_path = "%s/%s"%(base,line)
		
		result,point,img_pillow = check_img(number,image_path)
		# print(result,point)
		#画图
		draw = ImageDraw.Draw(img_pillow) # 在上面画画
		draw.rectangle([int(point[0]),int(point[1]),int(point[2]),int(point[3])], outline=(255,0,0)) # [左上角x，左上角y，右下角x，右下角y]，outline边框颜色
		img_pillow.show()
		strs = input('Please continue:')
		if strs == '1' and result == 1:
			fo.write("%s:%s \n"%(line,strs))
	else:
		print("%s is ok"%line)
fo.close()
